from django.shortcuts import render,redirect
from django.views import View
from django import http
import re
from users.models import User
from django.utils.decorators import method_decorator

# from django_redis.
from django_redis import get_redis_connection

#------ 这里，不用添加utils，不用修改自定义认证也可以的
from django.contrib.auth import login, logout, authenticate   #认证账号密码
from django.contrib.auth.decorators import login_required   #认证账号密码
#------

# Create your views here.

class RegisterView(View):
    # 用户注册
    def get(self, request):
        """
        提供注册界面
        :param request:
        :return:
        """
        return render(request, 'register_vue.html')   #在设置里面的DIR 设置路径

    def post(self, request):
        #1.初始化数据
        data=request.POST
        user_name=data.get('user_name')
        pwd=data.get('pwd')
        cpwd=data.get('cpwd')
        phone=data.get('phone')
        msg_code=data.get('msg_code')
        allow=data.get('allow')
        # 1,1 判断数据是否都有
        if not all([user_name, pwd, cpwd, phone, msg_code, allow]):
            return http.HttpResponseForbidden('参数不全')

        #1.2
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',user_name):
            return http.HttpResponseForbidden('用户格式有误')
        #1.3
        if not re.match(r'^[0-9A-Za-z]{8,20}$',pwd):
            return http.HttpResponseForbidden('密码格式有误')
        #1.4两遍密码是否相同
        if pwd !=cpwd:
            return http.HttpResponseForbidden('两遍密码不同')
        #1.5校验手机号码
        if not re.match(r'^1[3-9]\d{9}',phone):
            return http.HttpResponseForbidden('手机号码格式不正确')

        #1.6校验短信验证码
        redis_conn=get_redis_connection('verify_code')
        redis_sms_code=redis_conn.get('sms_%s'%phone).decode()
        if msg_code !=redis_sms_code:
            return http.HttpResponseForbidden('短信验证码错误')

        if allow !='on':
            return http.HttpResponseForbidden('请遵循用户守则')

        #2.处理业务
        #2.1创建用户
        try:
            user = User.objects.create_user(username=user_name, password=pwd, mobile=phone)
        except Exception as e:
            print(e)
            # return render(request, 'register_vue.html', {'register_errmsg': '注册失败'})
            return http.HttpResponseForbidden('注册失败')

        #3.返回响应
        # return redirect('www.//jd.com')
        # # pass
        return redirect('http://www.jd.com')

        pass

class UsernameCountView(View):
    def get(self,request,username):
        #1.初始化数据
        pass
        #2.处理业务逻辑
        # court=User.objects.filter(username=username).court()  #court字母写错，count
        count = User.objects.filter(username=username).count()

        #3.返回模型
        res={
            'code':0,
            'errmsg':'success',
            'count':count
        }
        return http.JsonResponse(res)

#用户名重复检测
class MobileCountView(View):
    def get(self,request,mobile):
        #1.初始化数据
        pass
        #2.处理业务逻辑
        count = User.objects.filter(mobile=mobile).count()
        #3.返回响应
        res={

            'code':0,
            'errmsg':'success',
            'count':count
        }
        return http.JsonResponse(res)

class LoginView(View):
    def get(self,request):
        return render(request,'login.html')
        pass

    def post(self,request):
        #1.初始化数据，获取数据，校验数据
        username=request.POST.get('username')
        password=request.POST.get('pwd')
        remembered=request.POST.get('remembered')
        if not all([username,password,remembered]):
            return http.HttpResponseForbidden('参数不全')
        if  not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return http.HttpResponseForbidden('用户名格式错误')
        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return http.HttpResponseForbidden('密码格式错误')

        #2.处理业务逻辑
        #第一种方法
        # try:
        #     username=User.objects.get(username=username)
        # except Exception as e:
        #     return http.HttpResponseForbidden('用户名不正确')
        # if user.check_password(password):
        #     return http.HttpResponseForbidden('密码不正确')
        # login(request,user)
 #----------------***或使用***--------------------------------
       #第二种方法 # user = authenticate(username=username, password=password)
        # if not user:
        #     return http.HttpResponseForbidden('用户名密码错误!')
        #login(request, user)

        # 认证登录用户
        #第三种方法
        #没修改自定义认证之前的
        user = authenticate(username=username, password=password,mobile=username)
        #修改自定义认证之后的
        user = authenticate(username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})

        # 3.返回响应
        response=redirect('/')
        response.set_cookie('username',user.username)

        return response
        pass

class LogoutView(View):
    def get(self,request):
        #1.初始化数据
        #2.处理业务逻辑
        logout(request)
        #3.返回数据
        response=redirect('/')
        response.delete_cookie('username')
        return response

# @method_decorator(login_required,name='dispatch')
class LoginRequiedView(View):  #View是大写的注意
    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

class UserCenterView(LoginRequiedView):
    # @method_decorator(login_required)
    def get(self,request):
        #1.判断用户是否是登陆状态，如果不是跳转到登陆页面
        #使用user自带的 is_authenticated() 方法判断是否是登陆状态
        # if request.user.is_authenticated():
        #     pass
        # else:
        #     return redirect('/login/')
        return render(request,'user_center_info.html')

